//
//  JCVerificationCell.swift
//  JChat
//
//  Created by JIGUANG on 2017/4/6.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import JMessage
import MTCategory

protocol JCVerificationCellDelegate: NSObjectProtocol {
    
    /// 同意申请信息
    /// - Parameters:
    ///   - userName: 同意的用户信息
    ///   - eventType: 事件类型1同意加好友，2同意加俱乐部
    ///   - pushId: 群组ID
    func acceptInvitation(userName: String, eventType: Int, pushId: String?)
}

class JCVerificationCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.backgroundColor = UIColor.theme.background
        setupUI()
        makeConstraint()
    }
    
    open class func reuseIdentity() -> String {
        return "JCVerificationCellID"
    }
    
    weak var delegate: JCVerificationCellDelegate?
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        makeConstraint()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupUI()
        makeConstraint()
    }
    
    func bindData(_ info: JCVerificationInfo) {
        
        /// 影藏不相关的控件
//        timeStatusLabel.isHidden = true
//        cycleView.isHidden = true
//        confrimBtn.isHidden = true
//        rejectBtn.isHidden = true
        
        self.info = info
        if info.nickname.isEmpty {
            nameLabel.text = info.type == .group ? info.initiator : info.username
        } else {
            nameLabel.text = info.type == .group ? info.initiator : info.nickname
        }
        
        let isSelf: Bool = JMSGUser.myInfo().username == info.initiator
        
        avatorImgV.image = UIImage(named: defaultPlaceholderIcon60x60)
        /// 是进入俱乐部的申请消息
        if info.type == .group {
            groupName(groupId: info.username)
            switch info.state {
            case JCVerificationType.wait.rawValue: /// 发送方等待确认好友申请
                //descLabel.text = isSelf ? info.resaon == "" ? "俱乐部请求已发送" : info.resaon : "请求加入\(info.nickname)俱乐部"
                cycleView.isHidden = true
                timeStatusLabel.isHidden = true
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = true
            case JCVerificationType.receive.rawValue: /// 等待确认好友申请
                //descLabel.text = isSelf ? info.resaon == "" ? "俱乐部请求已发送" : info.resaon : "请求加入\(info.nickname)俱乐部"
                timeStatusLabel.isHidden = true
                cycleView.isHidden = true
                confrimBtn.isHidden = false
                rejectBtn.isHidden = false
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = true
            case JCVerificationType.accept.rawValue:
                //descLabel.text = isSelf ? "同意了你的俱乐部请求" : "已通过俱乐部申请"
                timeStatusLabel.isHidden = false
                timeStatusLabel.text = updateTimeToCurrennTime(timeStamp: self.info.timestamp)
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = false
                verficationStatusLabel.text = "已通过"
            case JCVerificationType.reject.rawValue:
                //descLabel.text = isSelf ? "对方拒绝了你的俱乐部请求" : "已拒绝俱乐部申请"
                timeStatusLabel.isHidden = true
                cycleView.isHidden = true
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                verficationStatusLabel.isHidden = false
                verficationStatusLabel.text = "已拒绝"
                giftBtn.isHidden = true
            default:
                break
            }
        } else { /// 好友申请状态下的验证消息
            //descLabel.text = "申请添加好友"
            switch info.state {
            case JCVerificationType.wait.rawValue: /// 发送方等待确认好友申请
                descLabel.text = isSelf ? "好友申请已发送,等待对方验证" : info.resaon //info.resaon : "申请加好友"// "请求添加您为好友"
                cycleView.isHidden = true
                timeStatusLabel.isHidden = true
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = true
            case JCVerificationType.receive.rawValue: /// 等待确认好友申请
                //descLabel.text = info.resaon
                descLabel.text = isSelf ? "好友申请已发送,等待对方验证" : info.resaon
                timeStatusLabel.isHidden = true
                cycleView.isHidden = true
                confrimBtn.isHidden = false
                rejectBtn.isHidden = false
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = true
            case JCVerificationType.accept.rawValue:
                //descLabel.text = isSelf ? "同意了你的好友请求" : "已通过"
                descLabel.text = isSelf ? "同意了你的好友请求" : info.resaon
                timeStatusLabel.isHidden = false
                timeStatusLabel.text = updateTimeToCurrennTime(timeStamp: self.info.timestamp)
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                giftBtn.isHidden = true
                verficationStatusLabel.isHidden = false
                verficationStatusLabel.text = "已通过"
            case JCVerificationType.reject.rawValue:
                //descLabel.text = isSelf ? "对方拒绝了你的好友请求" : "已拒绝"
                descLabel.text = isSelf ? "对方拒绝了你的好友请求" : info.resaon
                timeStatusLabel.isHidden = true
                cycleView.isHidden = true
                confrimBtn.isHidden = true
                rejectBtn.isHidden = true
                verficationStatusLabel.isHidden = isSelf
                verficationStatusLabel.text = "已拒绝"
                giftBtn.isHidden = !isSelf
            default:
                break
            }
        }
        
        
        JMSGUser.userInfoArray(withUsernameArray: [info.type == .group ? info.initiator : info.username]) { (result, error) in
            if error == nil {
                let users = result as! [JMSGUser]
                let user = users.first
//                user?.thumbAvatarData({ (data, id, error) in
//                    if let data = data {
//                        let image = UIImage(data: data)
//                        self.avatorImgV.image = image
//                    }
//                })
                self.avatorImgV.mtSetImage(user?.avatar, nil)
                self.nameLabel.text = user?.displayName()
            }
        }
    }
    
    private func groupName(groupId: String) {
        JMSGGroup.groupInfo(withGroupId: groupId) { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            if let g: JMSGGroup = result as? JMSGGroup, let gName = g.name, error == nil {
                weakSelf.descLabel.text = "请求加入俱乐部\(gName)"
            } else {
                weakSelf.descLabel.text = "请求加入俱乐部"
            }
        }
    }
    
    private var info: JCVerificationInfo!
//    private lazy var iconView: UIImageView = UIImageView()
//    private lazy var nickname: UILabel = UILabel()
//    private lazy var reason: UILabel = UILabel()
//    private lazy var tipInfo: UILabel = UILabel()
    
    func setupUI() {
        contentView.addSubview(avatorImgV)
        contentView.addSubview(nameLabel)
        contentView.addSubview(descLabel)
        contentView.addSubview(lineView)
        
        contentView.addSubview(timeStatusLabel)
        contentView.addSubview(verficationStatusLabel)
        contentView.addSubview(cycleView)
        
        contentView.addSubview(confrimBtn)
        contentView.addSubview(rejectBtn)
        
        contentView.addSubview(giftBtn)
    }
    
    func makeConstraint() {
        avatorImgV.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(44)
        }
        
        nameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(avatorImgV.snp.right).offset(11)
            make.bottom.equalTo(contentView.snp.centerY).offset(-2)
        }
        
        descLabel.snp.makeConstraints { (make) in
            make.left.equalTo(nameLabel)
            make.top.equalTo(contentView.snp.centerY).offset(2)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        /// 状态显示相关
        cycleView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(timeStatusLabel.snp.left).offset(-7)
            make.width.height.equalTo(8)
        }
        
        timeStatusLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(verficationStatusLabel.snp.left).offset(-16)
        }
        
        verficationStatusLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
            make.width.equalTo(51)
            make.height.equalTo(31)
        }
        
        /// 好友请求操作
        confrimBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
        }
        
        rejectBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(confrimBtn.snp.left).offset(-16)
        }
        
        /// 礼物
        giftBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
        }
    }
    
    lazy var avatorImgV: UIImageView = {
        let imgV: UIImageView = UIImageView()
        imgV.contentMode = .scaleAspectFill
        imgV.clipsToBounds = true
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 22
        return imgV
    }()
    
    lazy var nameLabel: UILabel = {
        let lbl: UILabel = UILabel()
        lbl.textColor = UIColor(hex: 0xFFFFFF)
        lbl.font = PingFangSCMediumFont(14)
        lbl.numberOfLines = 1
        lbl.sizeToFit()
        return lbl
    }()
    
    lazy var descLabel: UILabel = {
        let lbl: UILabel = UILabel()
        lbl.textColor = ListViewSubTitleColor
        lbl.font = PingFangSCRegularFont(12)
        lbl.numberOfLines = 1
        lbl.sizeToFit()
        return lbl
    }()
    
    lazy var lineView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    /// 时间显示方面
    lazy var cycleView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor(hex: 0xFFC000)
        v.layer.cornerRadius = 4
        return v
    }()
    
    lazy var timeStatusLabel: UILabel = {
        let lbl: UILabel = UILabel()
        lbl.textColor = xF3F3F3Color
        lbl.font = PingFangSCRegularFont(12)
        lbl.numberOfLines = 1
        lbl.sizeToFit()
        return lbl
    }()
    
    /// 好友操作相关
    lazy var rejectBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("拒绝", for: .normal)
        btn.setTitleColor(ListViewSubTitleColor, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(12)
        btn.addTarget(self, action: #selector(reject), for: .touchUpInside)
        return btn
    }()
    
    lazy var confrimBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("同意", for: .normal)
        btn.setTitleColor(UIColor(hex: 0xFFC000), for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(12)
        btn.addTarget(self, action: #selector(confirm), for: .touchUpInside)
        return btn
    }()
    
    /// 礼物相关
    lazy var giftBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("送TA礼物", for: .normal)
        btn.setTitleColor(UIColor(hex: 0xFFC000), for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(12)
        btn.addTarget(self, action: #selector(gift), for: .touchUpInside)
        return btn
    }()
    
    lazy var verficationStatusLabel: UILabel = {
        let lbl: UILabel = UILabel()
//        lbl.textColor = xF3F3F3Color
        lbl.font = PingFangSCRegularFont(12)
        lbl.numberOfLines = 1
        lbl.textAlignment = .center
        lbl.backgroundColor = UIColor.theme.main
        lbl.layer.cornerRadius = 5
        lbl.layer.masksToBounds = true
        lbl.sizeToFit()
        return lbl
    }()
    
    @objc func gift() {
        AlertManager.presentGiftView(didClickRechargeCallBack: { [weak self] in
            guard let weakself = self else { return }
            
            if UserDefaults.AppValidate.isValidate.storedBool == false {
                let c = MTPaymentViewController()
                weakself.viewController?.navigationController?.pushViewController(c, animated: true)
            } else {
                let c = MTInAppPurchasesViewController()
                weakself.viewController?.navigationController?.pushViewController(c, animated: true)
            }
        }, selectedGiftCallBack: nil)
    }
    
    @objc func reject() {
        if self.info.type == .single {
            JMSGFriendManager.rejectInvitation(withUsername: info.username, appKey: info.appkey, reason: "拒绝了你的好友请求") { (result, error) in
                if error == nil {
                    self.info.state = JCVerificationType.reject.rawValue
                    JCVerificationInfoDB.shareInstance.updateData(self.info)
                    self.bindData(self.info)
                    NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
                }
            }
        } else {
            JMSGUser.userInfoArray(withUsernameArray: [self.info.initiator]) { (result, error) in
                if error == nil, let users = result as? [JMSGUser], users.count > 0, let u = users.first {
                    JMSGGroup.processApplyJoinEventID(self.info.eventId, gid: self.info.username, join: u, apply: u, isAgree: false, reason: nil) { [weak self] (result, error) in
                        guard let weakSelf = self else { return }
                        if error == nil {
                            weakSelf.info.state = JCVerificationType.reject.rawValue
                            JCVerificationInfoDB.shareInstance.updateData(weakSelf.info)
                            weakSelf.bindData(weakSelf.info)
                        }
                    }
                }
            }
        }
    }
    
    @objc func confirm() {
        
        if self.info.type == .single {
            JMSGFriendManager.acceptInvitation(withUsername: info.username, appKey: info.appkey) { (result, error) in
                if error == nil {
                    self.info.state = JCVerificationType.accept.rawValue
                    JCVerificationInfoDB.shareInstance.updateData(self.info)
                    self.bindData(self.info)
                    NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
                    self.delegate?.acceptInvitation(userName: self.info.username, eventType: MTRequestVerifyType.single.rawValue, pushId: nil)
                }
            }
        } else {
            JMSGUser.userInfoArray(withUsernameArray: [self.info.initiator]) { (result, error) in
                if error == nil, let users = result as? [JMSGUser], users.count > 0, let u = users.first {
                    JMSGGroup.processApplyJoinEventID(self.info.eventId, gid: self.info.username, join: u, apply: u, isAgree: true, reason: nil) { [weak self] (result, error) in
                        guard let weakSelf = self else { return }
                        if error == nil {
                            weakSelf.info.state = JCVerificationType.accept.rawValue
                            JCVerificationInfoDB.shareInstance.updateData(weakSelf.info)
                            weakSelf.bindData(weakSelf.info)
                            weakSelf.delegate?.acceptInvitation(userName: weakSelf.info.initiator, eventType: MTRequestVerifyType.group.rawValue, pushId: weakSelf.info.username)
                        }
                    }
                }
            }
        }
        
        
        
    }
    
    func updateTimeToCurrennTime(timeStamp: Double) -> String {
        //获取当前的时间戳
        cycleView.isHidden = true
        let currentTime = Date().timeIntervalSince1970
        debugPrint(currentTime,   timeStamp, "sdsss")
        //时间差
        let reduceTime : TimeInterval = currentTime - timeStamp
        //时间差小于60秒
        if reduceTime < 60 {
            cycleView.isHidden = false
            return "刚刚"
        }
        //时间差大于一分钟小于60分钟内
        let mins = Int(reduceTime / 60)
        if mins < 60 {
            return "\(mins)分钟前"
        }
        let hours = Int(reduceTime / 3600)
        if hours < 24 {
            return "\(hours)小时前"
        }
        let days = Int(reduceTime / 3600 / 24)
        if days < 30 {
            return "\(days)天前"
        }
        //不满足上述条件---或者是未来日期-----直接返回日期
        let date = NSDate(timeIntervalSince1970: timeStamp)
        let dfmatter = DateFormatter()
        //yyyy-MM-dd HH:mm:ss
        dfmatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
        return dfmatter.string(from: date as Date)
    }

}
